#include <stdio.h>
#include <stdlib.h>
#include "Register.h"
#include "DataBean.h"
#include "com_wish_jni_NativeLibrary.h"
#include "protocalParsing.h"
#include <jni.h>

struct jni_data_bean_t wishProtocalPasing(char inputDataArray[], int inputDataLen)
{
  jni_data_bean data_bean;
  COM_COM_TYPE *pCom;
  UNION_4_BYTE tmp4;
  UNION_2_BYTE tmp2;

  pCom = (COM_COM_TYPE *)&inputDataArray[0];

  tmp4.byte[0] = (uint8)pCom->head.pkLen[0];
  tmp4.byte[1] = (uint8)pCom->head.pkLen[1];
  tmp4.byte[2] = (uint8)pCom->head.pkLen[2];
  tmp4.byte[3] = (uint8)pCom->head.pkLen[3];

  // printf("inputDataLen=%x \n", inputDataLen);
  uint32 recCtxLen = (uint32)(tmp4.lword);
  // printf("recCtxLen=%x \n", recCtxLen);

  if ((recCtxLen + 3) != inputDataLen)
  {
    printf("recCtxLen=%d;inputDataLen=%d \n", recCtxLen, inputDataLen);
    data_bean.rtFlag = 0x1;
    return data_bean;
  }

  uint8 calSum = 0;
  uint16 i = 0;
  for (i = 0; i < recCtxLen; i++)
  {
    calSum += (uint8)inputDataArray[i + 1];
  }

  if (calSum != (uint8)inputDataArray[i + 1])
  {
    printf("err calSum=%x;inputCrcVal=%x ;idx=%d\n", calSum, (uint8)inputDataArray[i + 1], i);
    data_bean.rtFlag = 0x1;
    // return data_bean;
  }
  data_bean.rtFlag = 0x00;
  data_bean.version = 0x01;
  data_bean.pkLen = recCtxLen;
  tmp2.byte[0] = pCom->head.pkId[0];
  tmp2.byte[1] = pCom->head.pkId[1];
  data_bean.pkId = (uint32)tmp2.word;
  data_bean.pkCmd = pCom->head.packetCmd;
  data_bean.pkAck = (uint32)pCom->head.packetAnswer;

  // printf("data_bean.pkId =0x %x;data_bean.pkCmd=0x%x ;data_bean.pkAck=0x%x\n", data_bean.pkId, data_bean.pkCmd, data_bean.pkAck);
  if (pCom->head.packetAnswer != 0)
    goto end;

  uint8 *ptr = &pCom->buffer[HEAD_LEN];
  uint32 recvParaCtxLen = recCtxLen - HEAD_LEN - 2;
  data_bean.paraCnt = 0;
  uint16 oidLen;
  uint16 idx = 0;
  for (int i = 0; i < recvParaCtxLen; i += oidLen, idx++)
  {
    data_bean.paraCnt++;
    tmp2.byte[0] = *ptr++;
    tmp2.byte[1] = *ptr++;
    oidLen = tmp2.word;
    data_bean.ol[idx] =oidLen ;
    tmp2.byte[0] = *ptr++;
    tmp2.byte[1] = *ptr++;
    data_bean.oid[idx] = tmp2.word;
    if (oidLen <= 8)
    {
      for (uint16 j = 0; j < oidLen - 4; j++)
      {
        tmp4.byte[j] = *ptr++;
      }
      data_bean.val[idx] = tmp4.lword;
      // printf("  tmp4.val %x", tmp4.lword);
    }
    else
    {
      uint32 cnt = (oidLen - 4) / 2;
      for (int j = 0; j < cnt; j++)
      {
        tmp2.byte[0] = *ptr++;
        tmp2.byte[1] = *ptr++;
        data_bean.reportArrayVal[j] = (uint32)tmp2.word;
        // printf("   %x", data_bean.reportArrayVal[j]);
        // if(j%10 ==0)
        // {
        //   printf("  j=%d\n",j);
        // }
      }
    }
  }

end:
  return data_bean;
}
